from selenium.common.exceptions import NoSuchElementException


from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
import time, random, re
import datetime

from home.MyAutomator import MyAutomation

APP_PACKAGE = 'com.jifen.qukan'
APP_ACTIVITY = 'com.jifen.qkbase.main.MainActivity'

class Qu(MyAutomation):

    def __init__(self, APP_PACKAGE, APP_ACTIVITY):
        self.treasure_ele  = 'com.jifen.qukan:id/a1r'
        self.popup_ele = 'com.jifen.qukan:id/rv'
        self.home_ele = 'com.jifen.qukan:id/jp'
        self.coin_ele = 'com.jifen.qukan:id/xd'
        self.mission_ele = 'com.jifen.qukan:id/jt'
        self.video_ele = 'com.jifen.qukan:id/jq'
        self.content_ele = 'com.jifen.qukan:id/a6r'
        self.time_text_ele = 'com.jifen.qukan:id/a6s'
        self.svideo_ele = '//*[@text="小视频"]'   #com.jifen.qukan:id/jr
        self.sz_menu_ele = '//*[@text="科技"]'
        self.article_ele = 'com.jifen.qukan.content.shell:id/i8' #com.jifen.qukan.content.shell:id/i8
        self.return_ele = 'com.jifen.qukan:id/hq'
        self.picclose_ele = 'com.jifen.qukan:id/hr'
        self.tryplay_ele = '//*[@text="试玩领金币"]'
        # self.adclose_ele = '/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.RelativeLayout/android.widget.RelativeLayout[1]/android.view.View[1]'
        # self.cancel_ele = 'com.android.packageinstaller:id/cancel_button'
        # self.closead_ele = '//*[@text="关闭"]'
        self.videoclose_ele = 'com.jifen.qukan:id/mq'
        # self.new_ele = '//*[@resource-id="com.jifen.qukan:id/a8l"]/parent::android.widget.LinearLayout'
        # self.articlefa_ele = '//*[@resource-id="com.jifen.qukan:id/pc"]/android.widget.FrameLayout'
        # self.ad_ele = '//*[@text="广告"]'
        super().__init__(APP_PACKAGE, APP_ACTIVITY)

    # 首页弹窗
    def landing_page(self):
        try:
            treasure_pop = self.wait.until(EC.presence_of_element_located((By.ID, self.treasure_ele)))
            treasure_pop.click()
            print('关闭宝箱弹窗')
        except:
            print('没有宝箱弹窗')

    # 领币
    def get_coins(self):
        # try:
        #     pop_up = self.wait.until(EC.presence_of_element_located((By.ID, self.popup_ele)))
        #     pop_up.click()
        #     print('取消推送通知...')
        # except:
        #     print('无推送通知弹出框...')
        #     home = self.wait.until(EC.presence_of_element_located((By.ID, self.home_ele)))
        #     home.click()
        #     print('点击底部菜单:头条...')
        home = self.wait.until(EC.presence_of_element_located((By.ID, self.home_ele)))
        home.click()
        print('点击底部菜单:新闻...')
        try:
            coins = self.wait.until(EC.presence_of_element_located((By.ID, self.coin_ele)))
            time.sleep(2)
            if coins.get_attribute('text') == '领取':
                coins.click()
                print('领取金币')
                time.sleep(1)
            else:
                print('无金币可领取')
        except:
            pass

    # 签到
    def mission(self):
        mission = self.wait.until(EC.presence_of_element_located((By.ID, self.mission_ele)))
        mission.click()
        print('点击底部菜单:任务...')
        print('签到...')
        time.sleep(2)
        tryplay = self.wait.until(EC.presence_of_element_located((By.XPATH, self.tryplay_ele)))
        tryplay.click()
        print('试玩领金币...')


    # 视频
    def video(self, interval):
        video = self.wait.until(EC.presence_of_element_located((By.ID, self.video_ele)))
        video.click()
        print('点击底部菜单:视频...')
        time.sleep(random.randint(1, 3))
        t = 1
        start = time.time()
        while True:
            content = self.driver.find_elements_by_id(self.content_ele)
            time_text = self.driver.find_elements_by_id(self.time_text_ele)
            print('视频数量', len(content))
            n = 0
            try:
                for i in content:
                    print('第{}次进入循环... 点击第{}/{}个视频'.format(t,n+1,len(content)))
                    time_span = time_text[n].get_attribute('text').split(':')
                    time_cost = int(time_span[0]) * 60 + int(time_span[1])
                    i.click()
                    print('点击视频，时长:{}s'.format(time_cost))
                    time.sleep(time_cost)
                    n += 1
                    time.sleep(random.randint(4, 10))
            except IndexError:
                print('视频展示不完整')
            except NoSuchElementException:
                print('此为广告')
            t += 1
            self.swipeUp()
            time.sleep(random.randint(5, 10))
            end = start + interval
            now = time.time()
            if now >= end:
                print('结束视频循环')
                break

    # 小视频
    def smallvideo(self, interval):
        smallvideo = self.wait.until(EC.presence_of_element_located((By.XPATH, self.svideo_ele)))
        smallvideo.click()
        print('点击底部菜单:小视频...')
        start = time.time()
        while True:
            time.sleep(random.randint(5, 20))
            self.swipeUp()
            end = start + interval
            now = time.time()
            if now >= end:
                print('结束小视频循环')
                break

    # 阅读新闻
    def read_article(self, interval):
        try:
            pop_up = self.wait.until(EC.presence_of_element_located((By.ID, self.popup_ele)))
            pop_up.click()
            print('取消签到提醒...')
        except:
            print('无签到提醒弹出框...')
        # home = self.wait.until(EC.presence_of_element_located((By.ID, self.home_ele)))
        # home.click()
        # print('点击底部菜单:头条...')
        sz_menu = self.wait.until(EC.presence_of_element_located((By.XPATH, self.sz_menu_ele)))
        sz_menu.click()
        print('点击顶部菜单:subject...')
        start = time.time()
        while True:
            try:
                articles = self.wait.until(EC.presence_of_all_elements_located((By.ID, self.article_ele)))

                print('新闻数量', len(articles))
                for article in articles:
                    try:
                        article.click()
                        print('进入新闻')

                        print(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())))

                        try:
                            # return_btn = self.wait.until(EC.presence_of_element_located((By.ID, self.return_ele)))
                            for i in range(random.randint(2, 6)):
                                time.sleep(random.randint(6, 10))
                                self.swipeUp()
                            for i in range(random.randint(2, 6)):
                                time.sleep(random.randint(6, 10))
                                self.swipeDown()
                            # 返回
                            self.driver.press_keycode(4)
                            # return_btn.click()
                        except:
                            self.driver.keyevent(4)
                            print('没有虚拟返回键，返回 <')
                            time.sleep(random.randint(3, 6))

                        print('退出新闻进入菜单')
                    except:
                        self.swipeUp()
                for i in range(random.randint(2, 4)):
                    time.sleep(random.randint(1, 3))
                    print('菜单上海')
                    self.swipeUp()
                end = start + interval
                now = time.time()
                if now >= end:
                    print('结束新闻循环')
                    break
                else:
                    print('未到结束时间')
            except:
                self.swipeUp()


    # 入口函数
    def main(self):
        print('打开 {} App ...'.format('QU'))
        # self.mission()
        # func_list = ['smallvideo', 'read_article', 'video']  # 新闻，小视频，视频三个方法随机
        func_list = ['read_article']
        for i in range(12):
            # self.get_coins()
            exp = 'self.{}({})'.format(random.choice(func_list), random.randint(2000, 5000))
            print(exp)
            eval(exp)
            # home键
            self.driver.press_keycode(3)
            print('App {} 今日任务完成！'.format('QU'))


APP_PACKAGE = 'com.jifen.qukan'
APP_ACTIVITY = 'com.jifen.qkbase.main.MainActivity'

if __name__ == '__main__':
    qutoutiao = Qu(APP_PACKAGE, APP_ACTIVITY)
    qutoutiao.main()